package com.example.rocket.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * @description: JSON工具
 * @author TAO
 * @date 2021/12/21 11:43 上午
 */
public class JSONUtils {

    private static final ObjectMapper mapper = new ObjectMapper();

    public static byte[] writeAsBytes(Object obj){
        if (obj == null){
            return null;
        }
        try {
            return mapper.writeValueAsBytes(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T readValue(byte[] json , Class<? extends T> clazz){
        if (json == null || json.length == 0){
            return null;
        }
        try {
            return mapper.readValue(json,clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
